# !/usr/bin/python
# -*- coding: UTF-8 -*-
# 管理项目代码库分支
# 自动拉取代码库分支内容
# 自动提交子模块引用
from git import *
import jsonFileUtils
import os
import sys
import shutil
reload(sys)
sys.setdefaultencoding('utf8')
localEncoding = sys.getfilesystemencoding()

# ----------------代码库--------------
customerRepoPath = ''
gamesRepoPath = 'assets/resources/Game'
games_ProtoRepoPath = 'assets/resources/lib/Proto/game'
hall_ProtoRepoPath = 'assets/resources/lib/Proto'

def initRepos(workSpacePath):
    global customerRepoPath
    global gamesRepoPath
    global games_ProtoRepoPath
    global hall_ProtoRepoPath
    customerRepoPath = os.path.abspath(
        os.path.join(workSpacePath, customerRepoPath))

    gamesRepoPath = os.path.abspath(
        os.path.join(workSpacePath, gamesRepoPath))
    games_ProtoRepoPath = os.path.abspath(
        os.path.join(workSpacePath, games_ProtoRepoPath))
    hall_ProtoRepoPath = os.path.abspath(
        os.path.join(workSpacePath, hall_ProtoRepoPath))

    global customerRepo
    global gamesRepo
    global games_ProtoRepo
    global hall_ProtoRepo
    print('customerRepoPath =', customerRepoPath)
    print('gamesRepoPath =', gamesRepoPath)
    print('games_ProtoRepoPath =', games_ProtoRepoPath)
    print('hall_ProtoRepoPath =', hall_ProtoRepoPath)
    customerRepo = Repo(customerRepoPath)
    gamesRepo = Repo(gamesRepoPath)
    games_ProtoRepo = Repo(games_ProtoRepoPath)
    hall_ProtoRepo = Repo(hall_ProtoRepoPath)



def delUntrackedFileAndFolder(repoPath, repo):
    while len(repo.untracked_files) > 0:
        untrackedFilePath = os.path.abspath(
            os.path.join(repoPath, repo.untracked_files[0]))
        print('untrackedFilePath =%s' % untrackedFilePath)
        if os.path.isfile(untrackedFilePath):
            os.remove(untrackedFilePath)
        elif os.path.isdir(untrackedFilePath):
            shutil.rmtree(untrackedFilePath)


def changeBranch(repoPath, repo, branch):
    print('changing branch')
    curBranchName = ''
    try:
        curBranchName = repo.head.reference.name  #repo.active_branch.name
    except TypeError:
        # detached 状态
        curBranchName = branch

    if curBranchName != branch:
        branchExist = True
        try:
            # 存在则删除
            repo.git.branch('-D', branch)
        except GitCommandError:
            # 不存在则创建关联远端
            print('GitCommandError')
        remote = repo.remote()
        repo.head.reset(index=True, working_tree=True)
        delUntrackedFileAndFolder(repoPath, repo)
        repo.create_head(branch, remote.refs[branch]).set_tracking_branch(
            remote.refs[branch]).checkout()
        repo.head.reset(index=True, working_tree=True)
        delUntrackedFileAndFolder(repoPath, repo)
    else:
        repo.head.reset(index=True, working_tree=True)
        isExist = True
        try:
            # 存在则删除
            repo.git.checkout(branch)
        except GitCommandError:
            # 不存在则创建关联远端
            print('GitCommandError 1')
            isExist = False
        delUntrackedFileAndFolder(repoPath, repo)
        if isExist:
            repo.head.reference = repo.heads[branch]
        else:
            remote = repo.remote()
            repo.create_head(branch, remote.refs[branch]).set_tracking_branch(
                remote.refs[branch]).checkout()
        repo.head.reset(index=True, working_tree=True)
        delUntrackedFileAndFolder(repoPath, repo)


def autoChangeBranchs():
    print('---autoChangeBranchs---')
    customerRepoBranch = os.environ['CustomerBranch']
    gamesRepoBranch = os.environ['GamesBranch']
    hallprotoRepoBranch = os.environ['HallProtoBranch']
    gameprotoRepoBranch = os.environ['GameProtoBranch']

    print('拉取大厅皮和代码customerRepo curBranch=%s' % customerRepoBranch)
    changeBranch(customerRepoPath, customerRepo, customerRepoBranch)
    print('拉取子游戏子模块gamesRepo%s' % gamesRepoBranch)
    changeBranch(gamesRepoPath, gamesRepo, gamesRepoBranch)
    print('拉取大厅 proto子模块hallprotoRepo%s' % hallprotoRepoBranch)
    changeBranch(hall_ProtoRepoPath, hall_ProtoRepo, hallprotoRepoBranch)
    print('拉取游戏 proto子模块gamesprotoRepo%s' % gameprotoRepoBranch)
    changeBranch(games_ProtoRepoPath, games_ProtoRepo, gameprotoRepoBranch)


def pullBranch(repo):
    remote = repo.remote()
    remote.fetch()
    remote.pull()


def autoPullBranchs():
    print('---getGamesBranch---')
    pullBranch(customerRepo)
    print('----------拉取大厅代码 finish!---------')
    pullBranch(gamesRepo)
    print('----------拉取子游戏代码 finish!---------')
    pullBranch(hall_ProtoRepo)
    print('----------拉取大厅proto finish!---------')
    pullBranch(games_ProtoRepo)
    print('----------拉取子游戏proto finish!---------')

def commitBranch(repo):
    try:
        if repo.is_dirty():
            repo.git.add('.')
            repo.git.commit('-m', 'auto commit by old jenkins!')
    except GitCommandError:
        print('commitBranch GitCommandError')


def autoCommitBranchs():
    commitBranch(customerRepo)
    print('----------commit 大厅代码 finish!---------')
    commitBranch(gamesRepo)
    print('----------commit 子游戏代码 finish!---------')
    commitBranch(hall_ProtoRepo)
    print('----------commit 大厅proto finish!---------')
    commitBranch(games_ProtoRepo)
    print('----------commit 子游戏proto finish!---------')

def pushBranch(repo):
    remote = repo.remote()
    remote.push()


def autoPushBranchs():
    pushBranch(customerRepo)
    print('----------push 大厅代码 finish!---------')
    pushBranch(gamesRepo)
    print('----------push 子游戏代码 finish!---------')
    pushBranch(hall_ProtoRepo)
    print('----------push 大厅proto finish!---------')
    pushBranch(games_ProtoRepo)
    print('----------push 子游戏proto finish!---------')
